pro darksub, atv = atv
;+
; NAME:
;       DARKSUB
;
; PURPOSE:
; 	Subtracting a dark (or whatever image desired) from a set of FITS images
;
; INPUTS:
;
; OUTPUTS:
;
; KEYWORDS:
;
; EXAMPLE:
;	IDL> darksub
;
; REVISION HISTORY
;       Written by F. Hearty, CASA/CU-Boulder
;	Added header, comments - K. Willett, Jun 2007
;	Added ATV keyword - KW, Jul 07
;-

; Get filenames of images to be dark subtracted

filenames = dialog_pickfile(/multiple_files, filter = '*.fits', $
                            title = 'FITS file(s) to be dark subtracted')
nimages = n_elements(filenames)
if filenames(0) eq '' then begin
	print,'Did not select files to be dark subtracted'
	stop
endif

; Get filename of dark file to be subtracted

dark = dialog_pickfile(title = 'Dark FITS file', filter = '*.fits')

; Get path where dark-subtracted files are to be written

ds_path = dialog_pickfile(title = $
                          'Choose directory to write dark-subracted FITS', $
                          /directory)

; Read in dark image, convert to float

dark = float(mrdfits(dark, 0, darkhead, /unsigned))

; Begin loop over all images selected

for i = 0, nimages-1 do begin

	; Read in image, subtract dark, and extract the filename
	
	image = float(mrdfits(filenames[i], 0, header, /unsigned))
	image_ds = image - dark
	file_nopath = reverse(strsplit(filenames[i], '/', /extract))
	file_begin = strsplit(file_nopath[0], '.fits', /extract, /regex)
	ds_filename = file_begin[0] + '_ds.fits'
	
	; Write dark-subtracted image and original image header to file
	
	print, 'WRITING TO ' + ds_filename
	mwrfits, image_ds, ds_path + ds_filename, header

	if keyword_set(atv) then atv, image_ds

endfor

end
